<?php

namespace app\admin\controller;

use app\common\controller\AdminBase;
use think\App;
use think\exception\ValidateException;
use think\facade\Log;
use util\Excel;
/**
 * Dispute控制器
 */
class Orderstripe extends AdminBase
{

    protected $model = null;

    protected $validate = null;

    protected $relationSearch = false;

    public function __construct(App $app)
    {
        parent::__construct($app);

        $this->model = new \app\admin\model\OrderDispute();

        $this->validate = \app\admin\validate\OrderDispute::class;
    }

    
    /**
     * 列表
     */
    public function index()
    {
        $where2['type'] = 'stripe';
        list($limit, $where, $sortArr) = $this->buildTableParames();
        $list = $this->model
            ->where($where)
            ->where($where2)
            ->order('id desc')
            ->paginate($limit);
        $lists = $list->items();
        foreach ($lists as $k=>$v) {
            if($v['type'] == 'stripe'){
                $v = $this->change_stripe($v);
            }
            $lists[$k] = $v;
            $lists[$k]['status_alias'] = $this->switch_status($v);
            $lists[$k]['reason'] = $this->switch_reason($v);
            $site = table('site')
                ->where(['id' => $v['site_id']])->find();
            if(!empty($site)){
                $lists[$k]['site_name'] = $site['site_name'];
            }else{
                $lists[$k]['site_name'] = '未知';
            }
            if(empty($v['order_name'])){
                $lists[$k]['order_name'] = '未知';
            }
        }
        
        $data = [
            'code' => 1,
            'msg' => '',
            'count' => $list->total(),
            'data' => $lists,
        ];

        return json($data);
    }

    /**
    * 方法详情
    * @param array params
    */
    public function change_stripe($v)
    {
        if(!empty($v['amount'])){
            $v['amount'] = (float)number_format((float)$v['amount']/100, 2, '.', '');
        }
        if(!empty($v['createtime'])){
            if($this->is_timestamp($v['createtime'])){
                
            }else{
                $v['createtime'] = date('Y-m-d H:i:s', $v['createtime']);
            }
        }
        return $v;
    }

    function is_timestamp($string)
    {
        return (bool)strtotime($string);
    }
    /**
    * 方法详情
    * @param array params
    */
    public function change_paypal($v)
    {
        return $v;
    }
    /**
    * 方法详情
    * @param array params
    */
    public function switch_status($v)
    {
        switch ($v['status']) {
            case 'RESOLVED':
                $status_alias = '已解决';
                break;
            case 'WAITING_FOR_BUYER_RESPONSE':
                $status_alias = '需要买家回复';
                break;
            case 'WAITING_FOR_SELLER_RESPONSE':
                $status_alias = '需要卖家回复';
                break;
            case 'OPEN':
                $status_alias = '公开';
                break;
            case 'UNDER_REVIEW':
                $status_alias = '审查中';
                break;
            case 'OTHER':
                $status_alias = '其他';
                break;
            
            case 'warning_needs_response':
                $status_alias = '响应失败';
                break;
            case 'warning_under_review':
                $status_alias = '审查';
                break;
            case 'warning_closed':
                $status_alias = '关闭争议';
                break;
            case 'needs_response':
                $status_alias = '需要响应';
                break;
            case 'under_review':
                $status_alias = '正在审查';
                break;
            case 'charge_refunded':
                $status_alias = '费用退还';
                break;
            case 'won':
                $status_alias = '胜诉';
                break;
            case 'lost':
                $status_alias = '败诉';
                break;
            default:
            $status_alias = '未知';
        }
        return $status_alias;
    }
    /**
    * 方法详情
    * @param array params
    */
    public function switch_reason($v)
    {
        switch ($v['reason']) {
            case 'credit_not_processed':
                $reason = '贷记未处理';
                break;
            case 'duplicate':
                $reason = '重复扣款';
                break;
            case 'fraudulent':
                $reason = '欺诈';
                break;
            case 'general':
                $reason = '一般';
                break;
            case 'product_not_received':
                $reason = '未收到产品';
                break;
            case 'product_unacceptable':
                $reason = '产品不可接受';
                break;
            case 'subscription_canceled':
                $reason = '取消';
                break;
            case 'unrecognized':
                $reason = '无法识别';
                break;
            case 'CANCELED_RECURRING_BILLING':
                $reason = '已取消预核准付款';
                break;
            case 'CREDIT_NOT_PROCESSED':
                $reason = '未收到退款货退费';
                break;
            case 'DUPLICATE_TRANSACTION':
                $reason = '重复付款';
                break;
            case 'INCORRECT_AMOUNT':
                $reason = '金额或日期不正确';
                break;
            case 'MERCHANDISE_OR_SERVICE_NOT_AS_DESCRIBED':
                $reason = '物品与描述不符';
                break;
            case 'MERCHANDISE_OR_SERVICE_NOT_RECEIVED':
                $reason = '物品未收到';
                break;
            case 'OTHER':
                $reason = '其他';
                break;
            case 'PAYMENT_BY_OTHER_MEANS':
                $reason = '已使用其他方式付款';
                break;
            case 'UNAUTHORISED1':
                $reason = '未经交易的授权';
                break;
            default:
            $reason = $v['reason'];
        }
        return $reason;
    }
    /**
     * 查找
     */
    public function find()
    {
        $id= $this->request->get('id');
        $row = $this->model->find($id);
        if ($row['flag']) {
            $arr = explode(",", $row['flag']);
            foreach ($arr as $k => $v) {
                $arr[$k] = $v * 1;
            }
            $row['flag'] = $arr;
        } else {
            $row['flag'] = [];
        }
        if ($row['actdata']) {

            $arr = explode(",", $row['actdata']);
            foreach ($arr as $k => $v) {
                $arr[$k] = $v * 1;
            }
            $row['actdata'] = $arr;
        } else {
            $row['actdata'] = [];
        }
        if ($row['city']) {
            $row['city'] = explode(',', $row['city']);
        } else {
            $row['city'] = [];
        }
        if (empty($row)) {
            return error('数据不存在');
        }
        return success('ok', $row);
    }
    /**
     * 修改
     *
     */
    public function edit()
    {
        $id= input('id');
        $row = $this->model->find($id);
        if (empty($row)) {
            return error('数据不存在');
        }
        if ($this->request->isPost()) {
            $post = $this->request->post();
            try {
                $this->validate && validate($this->validate)->check($post);
                $result = $row->save($post);
                if ($result) {
                    return success('保存成功！');
                }
                return error('保存失败');
            } catch (ValidateException $e) {

                return error($e->getError());
            } catch (\Exception $e) {
                Log::error("--------:" . $e);
                return error('保存失败');
            }
        }
        if (empty($row)) {
            return error('数据不存在');
        }

        $row['status_alias'] = $this->switch_status($row);
        $row['reason'] = $this->switch_reason($row);
        $site = table('site')
            ->where(['id' => $row['site_id']])->find();
        if(!empty($site)){
            $row['site_name'] = $site['site_name'];
        }else{
            $row['site_name'] = '未知';
        }
        if(empty($row['order_name'])){
            $row['order_name'] = '未知';
        }
        //补充信息
        if($row['type'] == 'stripe'){
            $row = $this->change_stripe($row);
        }
        if($row['type'] == 'paypal'){
            $row = $this->change_paypal($row);
        }
        if(!empty($row['order_id'])){
            $order = table('order')
            ->where(['id' => $row['order_id']])->find();
            $row['customer_email_address'] = $order['email'];
            $row['address'] = $order['address1'];
            $row['customer_name'] = $order['shipping_name'];
        }

        return success('ok', $row);
    }

    /**
     * 导出
     */
    public function export()
    {
        list($limit, $where, $sortArr) = $this->buildTableParames();
        $fields = $this->request->get('fields');
        $fields = json_decode($fields, true);

        $header = [];
        foreach ($fields as $vo) {
            $header[] = [$vo['comment'], $vo['field']];
        }
        $tableName = $this->model->getName();
        $list = $this->model
            ->withJoin('category', 'LEFT')
            ->where($where)
            ->limit(100000)
            ->order($sortArr)
            ->select()
            ->toArray();
        $fileName = "export_" . $tableName . "_" . time();
        return Excel::exportData($list, $header, $fileName, 'xlsx');
    }
    
}